import { useEffect, useState, useRef } from 'react';
import { ModalForm, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { Card, Form, Divider, Row, Col } from "antd";
import { useModel } from 'umi';
import { getAccountList } from '@/services/permissions/api'
import { addSubDept, editSubDept } from '@/services/permissions/subDeptApi'
import { showMsg } from '@/utils/utils';

const EditForm = (props: EditFormProps) => {

  const { open, onOpenChange, subDept, finishCallback } = props;
  const [staffOptions, setStaffOptions] = useState<COMMON.SelectOption[]>([]);
  const { initialState: { currentUser = {} } } = useModel<any>('@@initialState');
  const formRef = useRef<ProFormInstance>();

  const save = async ({ manager_oper_id, ...obj }: FormType) => {
    try {
      const oper_name = staffOptions?.find(({ value }) => value === manager_oper_id)?.label.split(' - ')[1];
      let res;
      if (subDept) {
        res = await editSubDept({ ...obj, manager_oper_id, manager_oper_name: oper_name, sub_dept_code: subDept.sub_dept_code });
      } else {
        res = await addSubDept({ ...obj, manager_oper_id, manager_oper_name: oper_name });
      }
      if (res) {
        if (finishCallback) finishCallback();
        return true;
      }
    } catch (x: any) {
      showMsg(x.data?.errmsg || '保存失败');
    }
    return false;
  };

  useEffect(() => {
    getAccountList({ status: 'N', dept_level: 1, current: 1, pageSize: 9999 }).then(res => {
      setStaffOptions((res?.record_list || []).map(({ staff_code, oper_name }: any) => ({
        value: staff_code, label: staff_code + ' - ' + oper_name
      })));
    });
  }, []);

  useEffect(() => {
    if (subDept) {
      formRef.current?.setFieldsValue({ ...subDept, manager_oper_id: subDept?.manager_oper_id, status: subDept?.status ?? 'R' });
    } else {
      formRef.current?.resetFields();
    }
  }, [subDept]);

  return <>
    <ModalForm<FormType>
      title="新增/编辑二级部门"
      width={800}
      layout="horizontal"
      modalProps={{ okText: "保存", maskClosable: false, destroyOnClose: true }}
      formRef={formRef}
      onVisibleChange={onOpenChange}
      visible={open}
      labelAlign="right"
      onFinish={save}
    >
      <Card title="1.部门信息" bordered={false} className="dept-modal-card">
        <Row gutter={24}>
          <Col span={10}>
            <Form.Item label="业务科室" labelCol={{ flex: '0 0 90px' }}><span>{currentUser.dept_name}</span></Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={10}>
            <ProFormText label="部门名称" name="sub_dept_name" required labelCol={{ flex: '0 0 90px' }} rules={[{ required: true }]}></ProFormText>
          </Col>
          <Col span={14}>
            <ProFormText label="部门地址" name="address" required labelCol={{ flex: '0 0 70px' }} rules={[{ required: true }]}></ProFormText>
          </Col>
        </Row>
      </Card>
      <Card title="2.部门管理员" bordered={false} className="dept-modal-card">
        <Row gutter={24} style={{ marginTop: 12 }}>
          <Col span={10}>
            <ProFormSelect
              label="员工" name="manager_oper_id" required showSearch
              options={staffOptions as any} placeholder="请选择" labelCol={{ flex: '0 0 90px' }}
              rules={[{ required: true, message: '这是必选项' }]}
            >
            </ProFormSelect>
          </Col>
        </Row>
      </Card>
      <Divider style={{ borderTopColor: '#bbb' }}></Divider>
      <Card bordered={false} className="dept-modal-card" >
        <Row>
          <Col span={10}>
            <ProFormRadio.Group
              label="部门状态" name="status"
              labelCol={{ flex: '0 0 92px' }}
              required
              options={[
                { label: '启用', value: 'R' },
                { label: '停用', value: 'S' }
              ]}
            />
          </Col>
        </Row>
      </Card>
    </ModalForm>
  </>;
};

type FormType = Pick<PERMISSIONSAPI.SubDept, 'sub_dept_name' | 'address' | 'status' | 'manager_oper_id'>;

interface EditFormProps {
  open: boolean,
  onOpenChange: (value: boolean) => void,
  subDept?: PERMISSIONSAPI.SubDept,
  finishCallback?: () => void
}

export default EditForm;
